<?php
/*********************************************
  Dragonfly CMS, Copyright (c) 2004 by CPGNuke Dev Team
  http://dragonflycms.org
  Released under GNU GPL version 2 or any later version
**********************************************/

abstract class Dragonfly_Output_Css extends Dragonfly_Output_Tools
{

	protected static
		$files = array(),
		$inline = array(),
		$mtime = 0,
		$theme;

	final public static function add($file, $media='screen', $useLang=false)
	{
		$media = trim($media);
		if (!preg_match('#^([a-z0-9_]+/)?[a-z0-9_\\-\\.]+$#Di', $file)) { trigger_error('Invalid css file name: '.$file); return; }
		if (!preg_match('#^[a-z0-9:\\(\\)\\,\\- ]+$#Di', $media)) { trigger_error('Invalid css media string: '.$media); return; }
		self::$files[$media][$file] = $file;
	}

	final public static function inline($str, $media='screen')
	{
		self::$inline[$media][] = $str;
	}

	final public static function asynch($data)
	{
		return '<script type="text/javascript">
		var po = document.createElement("link");
		po.rel = "stylesheet";
		po.type = "text/css";
		po.href = "?css='.$data['src'].'";
		po.media = "'.$data['media'].'";
		document.getElementsByTagName("head")[0].appendChild(po);
</script>
';
	}

	final public static function request()
	{
		if (!isset(Dragonfly_Net_Http::$contentType['css'])) return false;
//		$_GET['css'] = gzinflate(base64_decode($_GET['css']));
		if (!preg_match('#^(([a-z0-9_]+/)?[a-z0-9_\\-\\.]+;)+$#Di', $_GET['css'].';')) return false;
		if (!preg_match('#^[a-z0-9_]+$#Di', $_GET['theme'])) return false;

		$theme = static::$theme = $_GET['theme'];
		$files = explode(';', $_GET['css']);
		$i = array_search('style', $files);
		if (0 !== $i) {
			if ($i) unset($files[$i]);
			array_unshift($files, 'style');
		}
		foreach ($files as $file)
		{
			$m = explode('/',$file);
			if (empty($m[1])) { $m[1] = $m[0]; }
			$options = array(
				"themes/{$theme}/style/{$file}.css",
				"themes/default/style/{$file}.css",
				"modules/{$m[0]}/style/{$m[1]}.css",
				"includes/css/{$file}.css",
				"includes/{$m[0]}/css/{$m[1]}.css",
			);
			foreach ($options as $file) {
				if (is_file($file)) {
					static::$files[] = $file;
					static::$mtime = max(static::$mtime, filemtime(BASEDIR.$file));
					break;
				}
			}
		}
		static::$files = array_values(array_unique(static::$files));
		return !empty(static::$files);
	}

	final public static function flushToClient()
	{
		parent::flushUsingCache('css');
	}

	final public static function flushToTpl()
	{
		global $CPG_SESS;

		$return = '';
		if (empty(self::$files)) return $return;

		self::add('custom');
		foreach (self::$files as $key => $val) {
			sort($val);
//			$val = base64_encode(gzdeflate(implode(';',$val)));
			if (version_compare(phpversion(), '5.4', '<')) {
				$href = http_build_query(array(
						'css'   => implode(';',$val),
						'theme' => $CPG_SESS['theme'],
						'lng'   => Dragonfly::getKernel()->L10N->lng
					), '', '&amp;');
			} else {
				$href = http_build_query(array(
						'css'   => implode(';',$val),
						'theme' => $CPG_SESS['theme'],
						'lng'   => Dragonfly::getKernel()->L10N->lng
					), '', '&amp;', PHP_QUERY_RFC3986);
			}

			$return .= "<link rel=\"stylesheet\" type=\"text/css\" media=\"{$key}\" href=\"?{$href}\"/>".DF_EOL;
		}
		self::$files = array();

		foreach (self::$inline as $key => $val) {
			$return .= '<style type="text/css" media="' .$key .'">';
			while ($str = array_shift($val)) {
				$return .= self::minify($str) .DF_EOL;
			}
			$return .= '</style>' .DF_EOL;
		}
		self::$inline = array();

		return DF_MODE_DEVELOPER ? $return : Dragonfly_Output_Xhtml::minify($return);
	}

	final public static function minify($str)
	{
		if (DF_MODE_DEVELOPER) return $str;
		$str = trim(preg_replace('#\s\s+#', ' ', $str));
		$str = preg_replace('#/\*.*?\*/#s', '', $str);
		$str = preg_replace('#\s*[^{}]+{\s*}\s*#', '', $str);
		$str = preg_replace('#\s*([{},;:])\s*#', '$1', $str);
		$str = str_replace(';}', '}', $str);
		return $str;
	}
}
